<template>
	<div class="index">
		<Header/>

		<div class="wrapper main">
			<div class="table-header wrapper">
				<div class="week-tab">
					<a href="" @click.prevent="prevWeek">&lt;&lt; Last Week</a>
					<span>Week Timetable</span>
					<a href="" @click.prevent="nextWeek">Next Week &gt;&gt;</a>
				</div>
				<a href="" class="back" @click.prevent="curWeek">Back to this week</a>
			</div>
			<div class="date-box">
				<div class="mark">
					<div>
						<i class="icon color0"></i>
						<span>Unavailable</span>
					</div>
					<div>
						<i class="icon color1"></i>
						<span>1:N Online</span>
					</div>
					<div>
						<i class="icon color2"></i>
						<span>Double Teachers</span>
					</div>
				</div>
				<div class="clear"></div>
			</div>
			<div class="table-box" v-loading="loading">
				<table>
					<thead>
						<tr>
							<th>Local time</th>
							<th v-for="(thead, index) in theadList">{{ weekNameList[index] }}<br/>{{ moment(thead).format('MM-DD') }}</th>
						</tr>
					</thead>
					<tbody>
						<tr v-for="(item, key, index) in tableList">
							<td width="128">{{ moment(timeList[index].Starttime).format('HH:mm') }}</td>
							<td width="156" v-for="td in item" :class="'color' + td.BackgroudColor" @mouseenter="getClassInfo($event, td.TimetableId)" @mouseleave="classId = ''">
								<span>{{ td.ClassName }}</span>
							</td>
						</tr>
					</tbody>
				</table>
			</div>

			<transition name="el-fade-in">
				<div class="popper" v-show="classId" @mouseenter="classId = classInfo.TimetableId" @mouseleave="classId = ''">
					<div class="con">
						<p><span>School :</span>{{ classInfo.InstitutionName }}</p>
						<p><span>Class :</span>{{ classInfo.ClassName }}</p>
						<p><span>Number :</span>{{ classInfo.TimetableStudentCount }}</p>
						<p><span>Course :</span>{{ classInfo.CourseName }}</p>
						<p><span>Form :</span>{{ classInfo.Form }}</p>
						<p><span>Teacher :</span>{{ classInfo.TeacherName }}</p>
						<p v-if="classInfo.TimeTableWay == 3">A Teacher:</span>{{ classInfo.AssistTeacher }}</p>
						<p><span>Date :</span>{{ moment(classInfo.StartTimestamps).format('YYYY/MM/DD') }} {{ moment(classInfo.EndTimestamps).format('dddd') }}</p>
						<p><span>Time :</span>{{ moment(classInfo.StartTimestamps).format('HH:mm') }}-{{ moment(classInfo.EndTimestamps).format('HH:mm') }}</p>
						<p><span>State :</span>{{ classInfo.State }}</p>
					</div>
					<el-row class="link">
						<el-button v-if="classInfo.EndTimestamps + 120000 > curTime" @click="enterClass(classInfo)" :class="{disabled: !classInfo.IsEnterOnlineRoom}" :disabled="!classInfo.IsEnterOnlineRoom">Enter Class</el-button>
						<el-button v-else @click="getVideoList(classInfo.ReturnVideoUrl)" :class="{disabled: classInfo.ReturnVideoUrl === '-1'}" :disabled="classInfo.ReturnVideoUrl === '-1'">Review</el-button>
						<el-button @click="leave(classInfo.TimetableId, classInfo.StartTimestamps, classInfo.EndTimestamps)" :class="{disabled: classInfo.IsEnterLeave}" :disabled="classInfo.IsEnterLeave">Leave</el-button>
					</el-row>
				</div>
			</transition>
		</div>
		<el-dialog width="60%" title="课程回放" :visible.sync="videoDialogVisible" :close-on-click-modal="false" @close="removeVideo">
			<el-tabs v-show="videoList.length > 1" @tab-click="switchVideo" v-model="activeName">
				<el-tab-pane v-for="(video, index) in videoList" :label="'视频' + (index + 1)" :name="'视频' + (index + 1)"></el-tab-pane>
			</el-tabs>
			<div class="video-box">
				<video-player class="video-player vjs-custom-skin" ref="videoPlayer" :playsinline="true" :options="playerOptions"></video-player>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import Header from '@/components/Header'

	export default {
		name: 'Index',
		components: {
			Header
		},
		data() {
			return {
				loading: true,
				tableList: {},
				timetable: [],
				classId: '',
				classInfo: {},
				weekNameList: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
				timeList: [],
				theadList: this.getWeekday(new Date()),
				sortIndex: 0,
				curTime: new Date().getTime(),
				videoDialogVisible: false,
				videoList: [],
				activeName: '视频1',
				playerOptions: {
					playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
					autoplay: false, //如果true,浏览器准备好时开始回放。
					muted: false, // 默认情况下将会消除任何音频。
					loop: false, // 导致视频一结束就重新开始。
					preload: false, // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
					language: 'zh-CN',
					aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
					fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
					sources: [{
						type: "",
						src: "" //视频url地址
					}],
					poster: "", //你的封面地址
					// width: document.documentElement.clientWidth,
					notSupportedMessage: '此视频暂无法播放，请稍后再试', //允许覆盖Video.js无法播放媒体源时显示的默认信息。
					controlBar: {
						timeDivider: true,
						durationDisplay: true,
						remainingTimeDisplay: false,
						fullscreenToggle: true  //全屏按钮
					}
				}
			}
		},
		created() {
			this.getTimeList()
		},
		methods: {
			// 初始化获取数据
			async getData() {
				this.loading = true
				
				const startDate = this.moment(this.theadList[0] + ' 00:00:00').valueOf()
				const endDate = this.moment(this.theadList[6] + ' 23:59:59').valueOf()

				const { ItemList } = await this.axios.get(`/OnlineTeacher/CourseTimetable/GetTimetableList?StartTimestamps=${startDate}&EndTimestamps=${endDate}`)

				this.loading = false

				ItemList.forEach(item => {
					item.pos = this.moment(item.StartTimestamps).format('YYYY-MM-DD HH:mm').split(' ')
				})

				this.timetable = ItemList
				
				this.createTable()
			},
			// 获取课程详情
			async getClassInfo(ev, id) {
				if (!id) return
				
				ev = ev || window.event
				
				let popperTop = ev.target.offsetTop + ev.target.offsetHeight
				let popperLeft = ev.target.offsetLeft + ev.target.offsetWidth/2

				document.querySelector('.popper').style.top = popperTop + 'px'
				document.querySelector('.popper').style.left = popperLeft + 'px'

				this.classId = id
				this.classInfo = {}

				const { TimetableInfo } = await this.axios.get(`/OnlineTeacher/CourseTimetable/GetTimetableInfo?timetableId=${id}`)

				if (TimetableInfo.StartTimestamps - this.curTime < 86400000) {
					this.$set(TimetableInfo, 'IsEnterLeave', true)
				}

				this.classInfo = TimetableInfo
			},
			// 获取时段
			async getTimeList() {
				let { TimetableInfo } = await this.axios.get('/OnlineTeacher/CourseTimetable/GetOnlineTimeList')

				// 获取时间段的截取位置
                for (let i = TimetableInfo.length - 1; i > 1; i--) {
                    if (new Date(TimetableInfo[i].Starttime).getHours() < new Date(TimetableInfo[i - 1].Starttime).getHours()) {
                        this.sortIndex = i
                        break
                    }
                }

                if (this.sortIndex) {
                    TimetableInfo = TimetableInfo.slice(this.sortIndex).concat(TimetableInfo.slice(0, this.sortIndex))
                }
				
				this.timeList = TimetableInfo
				this.getData()
			},
			// 创建表格并添加数据
			createTable() {
				this.tableList = {}

				// 创建表格
				for (let i = 0; i < this.timeList.length; i++) {
					const timeKey = this.moment(this.timeList[i].Starttime).format('HH:mm')

					this.tableList[timeKey] = {}

					for (let j = 0; j < 7; j++) {
						const dateKey = this.theadList[j]

						this.tableList[timeKey][dateKey] = {}
					}
				}
				
				// 添加数据
				for (let i = 0; i < this.timetable.length; i++) {
					const time = this.timetable[i].pos[1]
					const date = this.timetable[i].pos[0]

					if (this.tableList[time] && this.tableList[time][date]) {
						this.tableList[time][date] = this.timetable[i]
					}
				}
			},
			// 根据日期获取所在周
			getWeekday(date) {
				const currentDate = new Date(date)
				const timesStamp = currentDate.getTime()
				const currenDay = currentDate.getDay()

				let dates = []

				for (let i = 0; i < 7; i++) {
					dates.push(this.moment(timesStamp + 24 * 60 * 60 * 1000 * (i - (currenDay + 6) % 7)).format('YYYY-MM-DD'))
				}

				return dates
			},
			// 返回本周
			curWeek() {
				this.theadList = this.getWeekday(new Date())

				this.getData()
			},
			// 切换上一周
			prevWeek() {
				const prevDate = new Date(this.moment(this.theadList[0]).valueOf() - 23 * 60 * 60 * 1000)

				this.theadList = this.getWeekday(prevDate)

				this.getData()
			},
			// 切换下一周
			nextWeek() {
				const nextDate = new Date(this.moment(this.theadList[6]).valueOf() + 25 * 60 * 60 * 1000)

				this.theadList = this.getWeekday(nextDate)

				this.getData()
			},
			// 进入教室
			async enterClass(classInfo) {
				const isEnter = await this.axios.get(`/OnlineTeacher/CourseTimetable/GetAccountBalance?insititutionId=${classInfo.InstitutionId}`)

				if (isEnter.code != 1) {
					this.$message.error(isEnter.message)

					return
				}

				const res = await this.axios.get(`${classInfo.EnterClassroomURL}&access_token=${classInfo.AccessToken}`)

				if (res.Ret) {
					let url = res.Obj

					url = url.replace(/uname=C0.*&stype/, `uname=C0${classInfo.TeacherName}&stype`)
					
					window.open(url)
				}
			},
			// 课程回放初始化
			getVideoList(url) {
				this.videoList = url.split('|')
				this.playerOptions.sources[0].src = this.videoList[0]
				this.videoDialogVisible = true
			},
			// 切换视频播放
			switchVideo(tab) {
				this.playerOptions.sources[0].src = this.videoList[tab.index]
			},
			// 移除视频
			removeVideo() {
				document.querySelector('.video-box video').pause()
				this.activeName = '视频1'
			},
			// 请假
            leave(id, startTime, endTime) {
				const time = this.moment(startTime).format('MMMM Do YYYY') + ', ' + this.moment(startTime).format('HH:mm') + '-' + this.moment(endTime).format('HH:mm')

                this.$confirm(`Are you sure to Leave at ${time}?<span>After the leave, the course will be cancelled directly. Please operate with caution!</span>`, 'Tips', {
					customClass: 'leave-box',
					dangerouslyUseHTMLString: true
				}).then(async () => {
					const res = await this.axios.get(`/OnlineTeacher/CourseTimetable/ForeignTeacherAskForLeave?timetableId=${id}`)

					if (res.code === 1) {
						this.$message.success('Successful leave!')
						this.getData()
					} else {
						this.$message.error('Failure to ask for leave!')
					}
				}).catch(() => {})
            }
		}
	}
</script>

<style>
	.leave-box {width: 540px;}
	.leave-box .el-message-box__message {font-size: 16px;}
	.leave-box .el-message-box__message span {color: #9B9B9B; display: block; font-size: 14px;}
	.video-box video {outline: none;}
</style>

<style scoped>
	.main {padding-bottom: 50px;}

	.table-header {font-size: 0; text-align: center; margin: 30px auto;}
	.table-header .week-tab {font-size: 0; text-align: center;}
	.table-header .week-tab * {display: inline-block; color: #000;}
	.table-header .week-tab span {font-size: 36px; margin: 0 10px;}
	.table-header .week-tab a {font-size: 18px;}
	.table-header .back {color: #9B9B9B; position: absolute; right: 0; bottom: 8px; font-size: 16px;}

	.date-box .mark {float: right; margin-top: 20px;}
	.date-box .mark div {display: inline-block; margin-left: 12px;}
	.date-box .mark div * {display: inline-block; vertical-align: middle;}
	.date-box .mark i {width: 13px; height: 13px; margin-right: 4px;}
	.color0 {background: #E9E9EA;}
	.color1 {background: #FED127;}
	.color2 {background: #FA656E;}
	.date-box .mark span {color: #9B9B9B; font-size: 16px;}

	table {width: 100%; margin-top: 10px; border-collapse: collapse; border-spacing: 0;}
	table thead tr th {height: 50px; background: #D3E7FF; border-color: #5999E4;}
	table tr > * {height: 30px; border: 1px solid #BCDBFF; font-size: 12px; color: #00030A; text-align: center; position: relative;}
	table tr > *:first-child {border-color: #5999E4; background: #D3E7FF;}
	.popper {position: absolute; width: 216px; background: #4D84FC; border-radius: 4px; box-shadow: 0 0 10px rgba(77, 132, 252, .71); top: 0; left: 0; z-index: 1000;}
	.popper .con {padding: 5px 15px 11px;}
	.popper p {color: #fff; text-align: left; padding-top: 6px; font-size: 12px; white-space: nowrap;}
	.popper p span {display: inline-block; width: 50px; text-align: right; margin-right: 10px;}
	.popper .link {border-top: 1px solid rgba(255, 255, 255, .37); height: 50px; padding: 10px 0; text-align: center;}
	.popper .link .el-button {font-weight: normal; color: #4D84FC; font-size: 12px; padding: 0; width: 82px; height: 30px;}
	.popper .link .el-button + .el-button {margin-left: 20px;}
	.popper .link .el-button.disabled {opacity: .3;}
</style>